package com.help10000.rms.ui.activitys

import android.Manifest
import android.content.Intent
import android.content.IntentFilter
import android.graphics.drawable.Drawable
import android.graphics.drawable.StateListDrawable
import android.os.Build
import android.os.Bundle
import android.os.Looper
import android.util.TypedValue
import android.view.KeyEvent
import android.view.Menu
import android.widget.Toast
import androidx.core.view.get
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.amir.common.api.ApiContents
import com.amir.common.api.CustomObserver
import com.amir.common.beans.MenuData
import com.amir.common.beans.MenuListResponse
import com.amir.common.mvp.model.Model
import com.amir.common.mvp.presenter.BasePresenter
import com.amir.common.mvp.view.IView
import com.amir.common.utils.Constant
import com.amir.common.utils.GlideApp
import com.amir.common.utils.LogUtils
import com.amir.common.utils.PermissionUtils
import com.amir.common.utils.SPUtils
import com.amir.common.utils.ToastUtil
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.google.gson.Gson
import com.help10000.rms.R
import com.help10000.rms.common.PushExtraHelper
import com.help10000.rms.ui.adapter.MainFragmentAdapter
import com.help10000.rms.ui.base.BaseActivity
import com.help10000.rms.ui.fragments.ManagerFragment
import com.help10000.rms.ui.fragments.MineFragment
import com.help10000.rms.ui.fragments.WalletFragment
import com.help10000.rms.ui.fragments.WebFragment
import com.help10000.rms.ui.fragments.WorkOrderFragment
import com.help10000.rms.ui.utils.StatusBarUtil
import com.tencent.map.geolocation.TencentLocation
import com.tencent.map.geolocation.TencentLocationListener
import com.tencent.map.geolocation.TencentLocationManager
import com.tencent.map.geolocation.TencentLocationRequest
import kotlinx.android.synthetic.main.activity_main.bottom_navigat
import kotlinx.android.synthetic.main.activity_main.viewpage
import java.util.Timer
import java.util.TimerTask
import kotlin.system.exitProcess

class MainActivity : BaseActivity<BasePresenter<IView>, IView>(), TencentLocationListener {
    private var walletPosition: Int = 0
    private val fragments: MutableList<Fragment> = mutableListOf()
    private var mLocationManager: TencentLocationManager? = null

    //新增动态菜单相关变量
    private lateinit var menuDataList: List<MenuData>
    private val dynamicTitles = mutableListOf<String>()
    private val dynamicUrls = mutableListOf<String>()
    private var currentSelectedPosition = 0
    private var menuSwitchReceiver: MenuSwitchReceiver? = null

    override fun getlayoutId(): Int {
        return R.layout.activity_main
    }

    override fun initView() {
        isBlack = true
        bottom_navigat.itemIconTintList = null
//不需要启动获取权限
//        val permissions = arrayOf(
//            Manifest.permission.ACCESS_COARSE_LOCATION,
//            Manifest.permission.ACCESS_FINE_LOCATION,
//            Manifest.permission.READ_PHONE_STATE,
//            Manifest.permission.WRITE_EXTERNAL_STORAGE
//        )
//        val permissionsForQ = arrayOf(
//            Manifest.permission.ACCESS_COARSE_LOCATION,
//            Manifest.permission.ACCESS_FINE_LOCATION,
//            Manifest.permission.ACCESS_BACKGROUND_LOCATION,  //target为Q时，动态请求后台定位权限
//            Manifest.permission.READ_PHONE_STATE,
//            Manifest.permission.WRITE_EXTERNAL_STORAGE
//        )
//        if (Build.VERSION.SDK_INT >= 29) {
//            if (PermissionUtils.checkReadPermission(
//                    permissionsForQ, PermissionUtils.WriteAndRead, mContext
//                )
//            ) {
//                onLocationAddress()
//            }
//        } else {
//            if (PermissionUtils.checkReadPermission(
//                    permissions, PermissionUtils.WriteAndRead, mContext
//                )
//            ) {
//                onLocationAddress()
//            }
//        }

        // 初始化菜单数据
        loadMenuData()
    }

    override fun initData(savedInstanceState: Bundle?) {
        handleIntent(intent)
    }

    //菜单数据加载逻辑
    private fun loadMenuData() {
        /*SPUtils.getString("menu_cache")?.let {
            if(TextUtils.isEmpty(it)){
                LogUtils.I("TrackMenu menu_cache it=$it")
                return@let
            }
            menuDataList = Gson().fromJson(it, object : TypeToken<List<MenuData>>() {}.type)
            setupDynamicUI()
        }*/
        fetchMenuData()
    }

    // [!code ++] 网络请求菜单数据
    private fun fetchMenuData() {
        LogUtils.I("TrackMenu fetchMenuData")
        var accessToken = SPUtils.getString(Constant.AccessToken)
        val api=Model.getServer().menuList(accessToken)
        Model.getObservable(api, object : CustomObserver<MenuListResponse>(mvpView){
            override fun success(response: MenuListResponse) {
                LogUtils.I("TrackMenu fetchMenuData success response=$response")
                menuDataList = response.data.take(5)
                SPUtils.save("menu_cache", Gson().toJson(menuDataList))
                setupDynamicUI()
            }

            override fun onError(e: Throwable) {
                ToastUtil.show("请求数据失败!")
            }
        })
    }

    // 动态构建UI
    private fun setupDynamicUI() {
        LogUtils.I("TrackMenu setupDynamicUI")
        walletPosition = 0
        bottom_navigat.menu.clear()
        fragments.clear()
        dynamicTitles.clear()
        dynamicUrls.clear()

        menuDataList.forEachIndexed { index, data ->
            // 添加导航项，先设置一个占位图
            val menuItem = bottom_navigat.menu.add(Menu.NONE, index, Menu.NONE, data.Title)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                menuItem.icon = resources.getDrawable(R.drawable.ic_error_placeholder, null)
            }
            // 占位图（你可以替换为实际的占位图）
            // 异步加载图标并更新菜单项
            createIconStateAsync(data.Img, data.ImgActive) { stateDrawable ->
                runOnUiThread {
                    menuItem.icon = stateDrawable
                }
            }

            // 收集有效Fragment
            if("MY_BANK" == data.Url){
                walletPosition = index;
            }
            fragments.add(createFragment(data.Url,data.StatusBar))
            dynamicTitles.add(data.Title)
            dynamicUrls.add(data.Url)
        }

        // 配置ViewPager
        viewpage.apply {
            adapter = MainFragmentAdapter(supportFragmentManager, fragments, dynamicTitles)
            offscreenPageLimit = fragments.size
            addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
                override fun onPageScrolled(
                    position: Int,
                    positionOffset: Float,
                    positionOffsetPixels: Int
                ) {}

                override fun onPageSelected(position: Int) {
                    bottom_navigat.selectedItemId = position

                    val lastFragment = fragments[currentSelectedPosition]
                    if(lastFragment is WebFragment){
                        lastFragment.loadBlank();
                    }
                    val curFragment = fragments[position]
                    if(curFragment is WebFragment){
                        curFragment.reload();
                    }
                    currentSelectedPosition = position
                }

                override fun onPageScrollStateChanged(state: Int) {}
            })
        }

        bottom_navigat.selectedItemId = 0;
    }

    // 异步创建图标状态（使用 Glide 异步加载网络图片）
    private fun createIconStateAsync(
        normalPath: String,
        activePath: String,
        callback: (StateListDrawable) -> Unit
    ) {
        val stateDrawable = StateListDrawable()
        var normalLoaded = false
        var activeLoaded = false
        var normalDrawable: Drawable? = null
        var activeDrawable: Drawable? = null

        fun tryFinish() {
            if (normalLoaded && activeLoaded && normalDrawable != null && activeDrawable != null) {
                stateDrawable.addState(intArrayOf(android.R.attr.state_checked), activeDrawable)
                stateDrawable.addState(intArrayOf(), normalDrawable)
                callback(stateDrawable)
            }
        }

        loadNetworkDrawable(ApiContents.ImageUrl + normalPath) { drawable ->
            normalDrawable = drawable.mutate()
            normalLoaded = true
            tryFinish()
        }

        loadNetworkDrawable(ApiContents.ImageUrl + activePath) { drawable ->
            activeDrawable = drawable.mutate()
            activeLoaded = true
            tryFinish()
        }
    }

    // 异步加载网络 Drawable
    private fun loadNetworkDrawable(url: String, callback: (Drawable) -> Unit) {
        // 假设目标尺寸为 24dp
        val iconSizeInDp = 24f
        val iconSizeInPx = dpToPx(iconSizeInDp)

        GlideApp.with(this)
            .load(url)
            .override(iconSizeInPx, iconSizeInPx) // 强制调整图片大小
            .fitCenter() // 或者使用 centerCrop() 根据需求调整
            .into(object : CustomTarget<Drawable>() {
                override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
                    callback(resource)
                }

                override fun onLoadCleared(placeholder: Drawable?) {
                    // 可选：释放资源
                }
            })
    }

    // [!code ++] 创建Fragment实例
    private fun createFragment(url: String, statusBarColor: String): Fragment {
        return when (url) {
            "MY_WORKORDER" -> WorkOrderFragment.newInstance()
            "WORKORDER" -> ManagerFragment.newInstance(statusBarColor)
            "MY_BANK" -> WalletFragment.newInstance()
            "MY" -> MineFragment.newInstance()
            else -> WebFragment.newInstance(url,statusBarColor)
        }
    }

    override fun initListener() {
        bottom_navigat.setOnNavigationItemSelectedListener { item ->
            val position = item.itemId
            if (position >= menuDataList.size) return@setOnNavigationItemSelectedListener false

            val menuData = menuDataList[position]

            menuData?.let {
                LogUtils.I("TrackMenu OnNavigation position:$currentSelectedPosition   colorHex:${it?.StatusBar}")

                if(it?.Url.startsWith("http")){
                    StatusBarUtil.setColor(this@MainActivity,it?.StatusBar)
                }
                else{
                    StatusBarUtil.setColor(this@MainActivity,"")
                }
            }

            LogUtils.I("TrackMenu OnNavigation current=$currentSelectedPosition")
            viewpage.currentItem = position
            true
        }

        // 保留原有通知处理
        intent.extras?.getString("push_content")?.let {
            PushExtraHelper.handlePush(this, it)
        }


        menuSwitchReceiver = MenuSwitchReceiver()
        val intentFilter = IntentFilter()
        intentFilter.addAction( "com.action.menu.to_wallet")
        intentFilter.addAction( "com.action.menu.to_home")
        intentFilter.addAction( "com.action.menu.reload")
        registerReceiver(menuSwitchReceiver, intentFilter)
    }

    private inner class MenuSwitchReceiver : android.content.BroadcastReceiver() {
        override fun onReceive(context: android.content.Context?, intent: Intent?) {
            if (intent?.action == "com.action.menu.to_wallet") {
                LogUtils.I("TrackMenu to wallet onReceive $walletPosition")
                switchToWalletMenu()
            }
            else if (intent?.action == "com.action.menu.to_home") {
                LogUtils.I("TrackMenu to home onReceive ")
                switchToHome(intent?.getStringExtra("url"))
            }
            else if (intent?.action == "com.action.menu.reload") {
                LogUtils.I("TrackMenu reload onReceive")
                loadMenuData()
            }
        }
    }

    private fun switchToWalletMenu(){
        val actualIndex = walletPosition
        currentSelectedPosition = actualIndex;
        LogUtils.I("TrackMenu switchToWalletMenu actualIndex=$actualIndex")
        //viewpage.currentItem = actualIndex
        bottom_navigat.selectedItemId = actualIndex
    }

    public fun switchToHome(url: String?) {
        LogUtils.I("TrackMenu switchToHome url=$url")
        if(url.isNullOrEmpty()){
            currentSelectedPosition = 0;
            bottom_navigat.selectedItemId = currentSelectedPosition
        }
        else{
            currentSelectedPosition = dynamicUrls.withIndex().find {
                //LogUtils.I("TrackMenu switchToHome it=$it")
                it.value.equals(url, ignoreCase = true)
            }?.index ?: 0
            bottom_navigat.selectedItemId = currentSelectedPosition
        }
        LogUtils.I("TrackMenu switchToWalletMenu selectedPosition=$currentSelectedPosition")
    }

    var lastFragment = 0;

    //替换Fragment的方法
    private fun replaceFragment(fragment: Fragment) {
//        val fragmentManager: FragmentManager = supportFragmentManager
//        val transaction: FragmentTransaction = fragmentManager.beginTransaction()
//        transaction.replace(R.id.fragment_empty, fragment)
//        transaction.commit()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click()
        }
        return false
    }

    /**
     * 双击退出函数
     */
    private var isExit: Boolean? = false

    private fun exitBy2Click() {
        var tExit: Timer? = null
        if (isExit == false) {
            isExit = true // 准备退出
            Toast.makeText(this, "再按一次退出应用", Toast.LENGTH_SHORT).show()
            tExit = Timer()
            tExit.schedule(object : TimerTask() {
                override fun run() {
                    isExit = false // 取消退出
                }
            }, 2000) // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

        } else {
            finish()
            System.exit(0)
        }
    }


    /**
     * 定位
     */
    private fun onLocationAddress() {

        mLocationManager = TencentLocationManager.getInstance(this);
        val request = TencentLocationRequest.create()
        //用户可以自定义定位间隔，时间单位为毫秒，不得小于1000毫秒:
        //request.setInterval(30000);
        //设置请求级别
        request.setRequestLevel(TencentLocationRequest.REQUEST_LEVEL_ADMIN_AREA);
        //是否允许使用GPS
        request.setAllowGPS(true)
        //是否需要获取传感器方向
        request.setAllowDirection(true)
        //是否需要开启室内定位
        request.setIndoorLocationMode(true)
        //发起单次定位请求
        mLocationManager?.requestSingleFreshLocation(request, this, Looper.getMainLooper());
    }

    override fun onStatusUpdate(p0: String?, p1: Int, p2: String?) {
        LogUtils.I("P0:$p0\nP1:$p1\nP2:$p2 ")
    }

    override fun onLocationChanged(tencentLocation: TencentLocation?, p1: Int, p2: String?) {
        LogUtils.I("P0:$tencentLocation\nP1:$p1\nP2:$p2 ")
        if (tencentLocation != null) {
//            SPUtils.save(Constant.Latitude, tencentLocation.latitude)
//            SPUtils.save(Constant.Longitude, tencentLocation.longitude)
            SPUtils.save(Constant.Accuracy, tencentLocation.accuracy)
        }
    }

    override fun onNewIntent(intent: Intent?) {
//        super.onNewIntent(intent)
//        // 关键：更新当前 Activity 的 Intent 为新 Intent（可选，但推荐）
//        setIntent(intent)
//        // 处理新参数
//        if (intent != null) {
//            handleIntent(intent)
//        }
//        var index = intent?.extras?.getInt("check_index", -1);
//        LogUtils.I("TrackMenu onNewIntent index $index")
//        if (index != null && index >= 0) {
//            viewpage.currentItem = index
//            replaceFragment(fragment = fragments[index])
//            bottom_navigat.menu[index].isChecked = true;
//        } else {
//            finish()
//            exitProcess(0)
//        }
        super.onNewIntent(intent)
        if (intent != null) {
            // 保留原有check_index处理，但去掉错误的退出逻辑
            var index = intent.extras?.getInt("check_index", -1);
            LogUtils.I("TrackMenu onNewIntent index $index")
            if (index != null && index >= 0) {
                viewpage.currentItem = index
                bottom_navigat.menu[index].isChecked = true;
            } else {
                // 原有逻辑：finish() + exitProcess(0) 会直接退出，注释掉
                // 改为处理新参数
                setIntent(intent)
                handleIntent(intent) // 调用参数处理方法
            }
        }
    }
//不需要启动获取权限
//    override fun onRequestPermissionsResult(
//        requestCode: Int,
//        permissions: Array<out String>,
//        grantResults: IntArray
//    ) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
//        onLocationAddress()
//
//    }

    override fun onDestroy() {
        if (mLocationManager != null) {
            mLocationManager?.removeUpdates(this);
        }
        menuSwitchReceiver?.let {
            unregisterReceiver(it)
            menuSwitchReceiver = null
        }
        super.onDestroy()
    }

    // 将 dp 转换为 px 的方法
    fun dpToPx(dp: Float): Int {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dp,
            resources.displayMetrics
        ).toInt()
    }

    // MainActivity 中新增处理 TARGET_URL 参数的逻辑
    private fun handleIntent(intent: Intent) {
        // 1. 处理原有 check_index 参数
        val checkIndex = intent.getIntExtra("check_index", -1)
        if (checkIndex != -1) {
            viewpage.currentItem = checkIndex
            bottom_navigat.selectedItemId = checkIndex
            return
        }

        // 2. 处理从 OrderActivity 传递的 TARGET_URL 参数（核心修改）
        val targetUrl = intent.getStringExtra("TARGET_URL")
        if (!targetUrl.isNullOrEmpty()) {
            // 直接调用现有逻辑：根据 URL 切换到对应的 Fragment
            switchToHome(targetUrl)
            return
        }

        // 3. 其他原有逻辑（如默认首页）
        switchToHome(null)
    }
}